package com.apes.scm.masterdata.area.service;

import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.area.model.Country;
import com.apes.scm.masterdata.area.repository.CountryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 功能：地区--国家
 *
 * @author HuJianlin
 * @create 2018-03-06 14:35
 */
@Service("countryService")
public class CountryService {

    @Autowired
    CountryRepository countryRepository;

    public Country save(SimpleRequest request) {
        Country country = request.getO(Country.class);
        countryRepository.saveAndFlush(country);
        return country;
    }

    /**
     * 功能：
     *
     * @param request
     */
    public List<Country> findAll(SimpleRequest request) {
        List<Country> countries = countryRepository.findAll();
        return countries;
    }

    public Page<Country> find(SimpleRequest request) {
        return countryRepository.find(PageRequest.of(request.get("page"), request.get("size")) );
    }

    /**
     * 根据国家代码找
     * @param prefix
     * @return
     */
    public Country findByPrefix(String type,String prefix){
        Country country ;
        switch (type){
            case "ID":
                country = countryRepository.findOne(prefix);
                break;
            default:
                throw new RuntimeException("省份类型无效");
        }
        return country;
    }
}
